package com.tvapp;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.leanback.app.BrowseFragment;
import androidx.leanback.widget.ArrayObjectAdapter;
import androidx.leanback.widget.HeaderItem;
import androidx.leanback.widget.ImageCardView;
import androidx.leanback.widget.OnItemViewClickedListener;
import androidx.leanback.widget.OnItemViewSelectedListener;
import androidx.leanback.widget.Presenter;
import androidx.leanback.widget.Row;
import androidx.leanback.widget.RowPresenter;
import androidx.leanback.widget.VerticalGridPresenter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private BrowseFragment browseFragment;
    private ArrayObjectAdapter rowsAdapter;
    private List<Channel> channels = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        browseFragment = (BrowseFragment) getSupportFragmentManager().findFragmentById(R.id.main_browse_fragment);
        browseFragment.setTitle(getString(R.string.title_main));
        browseFragment.setHeadersState(BrowseFragment.HEADERS_ENABLED);
        browseFragment.setOnItemViewClickedListener(getItemViewClickedListener());
        browseFragment.setOnItemViewSelectedListener(getItemViewSelectedListener());

        // 初始化频道数据
        initChannels();
        // 设置适配器
        setupAdapter();
    }

    private void initChannels() {
        // 这里我们添加一些模拟的频道数据
        // 实际应用中，这些数据可能来自网络或本地存储
        channels.add(new Channel("1", "中央电视台综合频道", "http://192.168.1.11/stream/1", getString(R.string.category_recommended)));
        channels.add(new Channel("2", "中央电视台新闻频道", "http://192.168.1.11/stream/2", getString(R.string.category_news)));
        channels.add(new Channel("3", "中央电视台体育频道", "http://192.168.1.11/stream/3", getString(R.string.category_sports)));
        channels.add(new Channel("4", "中央电视台娱乐频道", "http://192.168.1.11/stream/4", getString(R.string.category_entertainment)));
        channels.add(new Channel("5", "北京卫视", "http://192.168.1.11/stream/5", getString(R.string.category_recommended)));
        channels.add(new Channel("6", "东方卫视", "http://192.168.1.11/stream/6", getString(R.string.category_recommended)));
        channels.add(new Channel("7", "湖南卫视", "http://192.168.1.11/stream/7", getString(R.string.category_entertainment)));
        channels.add(new Channel("8", "广东卫视", "http://192.168.1.11/stream/8", getString(R.string.category_recommended)));
    }

    private void setupAdapter() {
        rowsAdapter = new ArrayObjectAdapter(new CardPresenter());
        
        // 按分类分组频道
        Map<String, List<Channel>> channelsByCategory = new HashMap<>();
        for (Channel channel : channels) {
            if (!channelsByCategory.containsKey(channel.getCategory())) {
                channelsByCategory.put(channel.getCategory(), new ArrayList<>());
            }
            channelsByCategory.get(channel.getCategory()).add(channel);
        }

        // 为每个分类创建一行
        int headerId = 0;
        for (Map.Entry<String, List<Channel>> entry : channelsByCategory.entrySet()) {
            HeaderItem header = new HeaderItem(headerId++, entry.getKey());
            ArrayObjectAdapter listRowAdapter = new ArrayObjectAdapter(new CardPresenter());
            
            for (Channel channel : entry.getValue()) {
                listRowAdapter.add(channel);
            }
            
            rowsAdapter.add(new Row(header));
            rowsAdapter.addAll(rowsAdapter.size(), listRowAdapter);
        }

        browseFragment.setAdapter(rowsAdapter);
    }

    private OnItemViewClickedListener getItemViewClickedListener() {
        return new OnItemViewClickedListener() {
            @Override
            public void onItemClicked(Presenter.ViewHolder itemViewHolder, Object item, 
                                      RowPresenter.ViewHolder rowViewHolder, Row row) {
                if (item instanceof Channel) {
                    Channel channel = (Channel) item;
                    Log.d(TAG, "Clicked on channel: " + channel.getName());
                    // 启动播放器Activity
                    Intent intent = new Intent(MainActivity.this, PlayerActivity.class);
                    intent.putExtra("channel", channel);
                    startActivity(intent);
                }
            }
        };
    }

    private OnItemViewSelectedListener getItemViewSelectedListener() {
        return new OnItemViewSelectedListener() {
            @Override
            public void onItemSelected(Presenter.ViewHolder itemViewHolder, Object item, 
                                       RowPresenter.ViewHolder rowViewHolder, Row row) {
                if (item instanceof Channel) {
                    Channel channel = (Channel) item;
                    Log.d(TAG, "Selected channel: " + channel.getName());
                }
            }
        };
    }

    @Override
    public void onBackPressed() {
        // 处理返回键事件
        super.onBackPressed();
    }
}